#include "stdafx.h"
#include "Ant.h"
#include "GoHome.h"
#include "myRand.h"
#include "terrain.h"
#include "Dead.h"
#include "Thirsty.h"

extern int terrain[kMaxRows][kMaxCols];
extern CAnt antList[kMaxAnts];

CGoHome * CGoHome::instance()
{
	static CGoHome inst;
	return (&inst);
}

void CGoHome::Enter(CAnt *pAnt)
{
}

void CGoHome::Execute(CAnt *pAnt)
{
	int rowMove;
	int colMove;
	int newRow;
	int newCol;
	int homeRow;
	int homeCol;
	int index;
	int poisonRow,poisonCol;

	if(pAnt->type==kRedAnt){
		homeRow = kRedHomeRow;
		homeCol = kRedHomeCol;
	}
	else{
		homeRow = kBlackHomeRow;
		homeCol = kBlackHomeCol;
	}
	if(pAnt->row < homeRow)	rowMove = 1;
	else if(pAnt->row > homeRow)	rowMove = -1;
	else	rowMove = 0;

	if(pAnt->col < homeCol)	colMove = 1;
	else if(pAnt->col > homeCol)	colMove = -1;
	else	colMove = 0;

	newRow = pAnt->row + rowMove;
	newCol = pAnt->col + colMove;

	if(newRow < 0) return;
	if(newCol < 0) return;
	if(newRow >= kMaxRows -1) return;
	if(newCol >= kMaxCols -1) return;

	if(terrain[newRow][newCol] != kPoison){
		pAnt->row = newRow;
		pAnt->col = newCol;
	}
	else{
		pAnt->row = newRow;
		pAnt->col = newCol;
		terrain[pAnt->row][pAnt->col] = kGround;
		do{
			poisonRow = rnd(0,kMaxRows-1);
			poisonCol = rnd(0,kMaxCols-1);
		}while(terrain[poisonRow][poisonCol] != kGround);
		terrain[poisonRow][poisonCol] = kPoison;
		pAnt->changeState(CDead::instance());
//		state = kDead;
	}

	if((newRow == homeRow) && (newCol == homeCol)){
		pAnt->row = newRow;
		pAnt->col = newCol;
		for(index = 0; index < kMaxAnts; index++){
			if(antList[index].type == 0){
				antList[index].New(pAnt->type, homeRow, homeCol);
				CAnt::antNum++;
				break;
			}
		}

		pAnt->changeState(CThirsty::instance());
//		state = kThirsty;
	}
}

void CGoHome::Exit(CAnt *pAnt)
{
}
